package service

import (
	"strconv"
	"tiktok2023/model"
	"time"

	"github.com/gin-gonic/gin"
)

type FeedService struct {
}

type FeedListResponse struct {
	model.Response
	NextTime  int           `json:"next_time"`
	VideoList []model.Video `json:"video_list"`
}

func (f FeedService) HandleFeedList(c *gin.Context) (*FeedListResponse, error) {
	LastTimeStr := c.Query("latest_time")
	var lastTime int
	vedios := []model.Video{}
	videoTable := []model.VideosTable{}
	if LastTimeStr != "" {
		lastTime, _ = strconv.Atoi(LastTimeStr)
	} else {
		lastTime = int(time.Now().Unix())
	}
	if err := model.Db.Where("publish_time < ?", lastTime).Order("publish_time desc").Limit(30).Find(&videoTable).Error; err != nil {
		return nil, err
	}
	if len(videoTable) != 0 {
		lastTime = int(videoTable[0].PublishTime)
	}
	// 对返回的视频进行一些信息的绑定
	for i, _ := range videoTable {
		user := model.TableUser{}
		if err := model.Db.Where("id = ?", videoTable[i].AuthorId).Find(&user).Error; err != nil {
			return nil, err
		}
		vedio := model.Video{
			Id:       videoTable[i].Id,
			Author:   user,
			PlayUrl:  videoTable[i].PlayUrl,
			CoverUrl: videoTable[i].CoverUrl,
			Title:    videoTable[i].Title,
		}
		// 判断用户是否登录了
		token := c.Query("token")
		if len(token) != 0 {
			// 判断是否是用户点赞的
			userId := c.GetUint64("userId")
			if err := model.Db.Where("user_id = ? AND video_id = ? AND cancel = 0", userId, vedio.Id).First(&model.LikesTable{}).Error; err == nil {
				vedio.IsFavorite = true
			}
		}
		// 再查询该视频的点赞数和评论数
		if err := model.Db.Model(&model.LikesTable{}).Where("video_id = ? AND cancel = 0", vedio.Id).Count(&vedio.FavoriteCount).Error; err != nil {
			return nil, err
		}
		if err := model.Db.Model(&model.CommentTable{}).Where("video_id = ? AND cancel = 0", vedio.Id).Count(&vedio.CommentCount).Error; err != nil {
			return nil, err
		}
		vedios = append(vedios, vedio)
	}

	return &FeedListResponse{
		Response: model.Response{
			StatusCode: 0,
		},
		NextTime:  lastTime,
		VideoList: vedios,
	}, nil
}
